package com.blb.community_admin.util;

import com.alibaba.excel.EasyExcel;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;

/**
 * @author hkp
 * easyExcel工具类
 */
public class EasyExcelUtil {
    /**
     * 导出excel
     *
     * @param fileName 文件名
     * @param tClass   需要导出的类的Class对象
     * @param list     需要导出的数据
     * @return 返回文件路径
     */
    public static <T> String write(String fileName, Class<T> tClass, List<T> list) {
        String dirPath = System.getProperty("user.dir") + "/excel/" + tClass.getSimpleName() + "/";
        File file = new File(dirPath);
//        如果目录不存在，创建目录
        if (!file.exists()) {
            file.mkdirs();
        }
        String name = fileName + ".xlsx";
        name = dirPath + name;
        EasyExcel
                .write(name, tClass)
                .sheet()
                .doWrite(list);
        return name;
    }

    /**
     * 浏览器下载
     *
     * @param path
     * @throws IOException
     */
    public static ResponseEntity<ByteArrayResource> download(String path) throws IOException {
        File file = new File(path);
        byte[] data = Files.readAllBytes(file.toPath());
        ByteArrayResource bar = new ByteArrayResource(data);
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.length()).header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(path.substring(path.lastIndexOf("/") + 1), "UTF8").replace("+", "%20")).body(bar);
    }
}
